import { getBaseUrl } from '@/utils/env';
import { router } from '@/router';
import { useAuthStore } from '@/store/modules/auth';
const authStore = useAuthStore();
/**
 * 跳转
 * @param name 路由名称
 * @param params 参数
 * @param tabBar 是否tabBar
 * @param redirect 是否关闭当前页
 */
export function handleJump(name: string, params: Record<string, any> = {}, tabBar = false, redirect = false) {
    if (tabBar === true) {
        router.replaceAll({ name: name, params });
    } else {
        if (redirect === true) {
            router.replace({ name: name, params });
        } else {
            router.push({ name: name, params });
        }
    }
}

export function goBack(timeout = 2000) {
    setTimeout(() => {
        router.back();
    }, timeout);
}

/**
 * 下载文件
 * @param filepath 文件路径
 */
export function downloadFile(filepath: string) {
    console.log(123);
    console.log(filepath);
    const downloadTask = uni.downloadFile({
        url: filepath,
        success: (res) => {
            if (res.statusCode === 200) {
                console.log('下载成功');
            }
            const getFileSystemManager = uni.getFileSystemManager();
            getFileSystemManager.saveFile({
                tempFilePath: res.tempFilePath,
                success: function (red) {
                    console.log(red);
                    uni.showModal({
                        title: '提示',
                        content: '文件已保存：' + red.savedFilePath,
                        cancelText: '我知道了',
                        confirmText: '打开文件',
                        success: function (res) {
                            if (res.confirm) {
                                uni.openDocument({
                                    filePath: red.savedFilePath,
                                    success: (sus) => {
                                        console.log('成功打开');
                                    },
                                });
                            }
                        },
                    });
                },
            });
        },
        complete: () => {},
    });
    downloadTask.onProgressUpdate((res) => {
        console.log('下载进度' + res.progress);
        console.log('已经下载的数据长度' + res.totalBytesWritten);
        console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
        // 满足测试条件，取消下载任务。
        // if (res.progress > 50) {
        //     downloadTask.abort();
        // }
    });
}

//名字中间变*
export function formatNickname(val: string) {
    const len = val.length;
    let str = '';
    if (len <= 2) {
        str = val.substring(0, 1) + '*';
    } else {
        str = val.substring(0, 1) + '*' + val.substring(len - 1, len);
    }
    return str;
}

// 图片处理-选择图片
export function chooseMedia(count = 1, mediaType?: ('image' | 'video' | 'mix')[] | undefined) {
    return new Promise((resolve, reject) => {
        uni.chooseMedia({
            mediaType: mediaType,
            count: count, //默认9
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album'], //从相册选择
            success: (res) => {
                resolve(res.tempFiles);
            },
            fail: (err) => {
                reject(err);
            },
        });
    });
}

/**
 * 上传
 * @param url
 * @returns
 */
export function uploadFiels(url: string) {
    uni.showLoading({
        title: '上传中',
    });
    const baseurl = getBaseUrl();
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: baseurl + '/api/common/upload',
            filePath: url,
            name: 'file',
            header: { token: authStore.getToken },
            success: (res) => {
                const data = JSON.parse(res.data);
                if (data.code === 1) {
                    uni.hideLoading();
                    resolve(data.data);
                } else {
                    uni.hideLoading();
                    uni.showModal({
                        title: '上传失败',
                        content: data.msg,
                    });
                    reject(res);
                }
            },
            fail: (err) => {
                reject(err);
            },
        });
    });
}
// 数组对象转一维数组
export function two2One(array, key) {
    const arr = array.map(function (item) {
        return item[`${key}`];
    });
    return arr;
}
// js将数字转换成万、亿、万亿
export function moneyFormat(value) {
    let data = '';
    let k = 10000,
        sizes = ['', '万', '亿', '万亿'],
        i;
    if (value < k) {
        data = value;
    } else {
        i = Math.floor(Math.log(value) / Math.log(k));
        data = (value / Math.pow(k, i)).toFixed(1) + sizes[i];
    }
    return data;
}
